package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleDraftMapper;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleDraft;
import com.example.forum.model.User;
import com.example.forum.services.IArticleDraftService;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleDraftServiceImpl implements IArticleDraftService {

    @Resource
    private ArticleDraftMapper articleDraftMapper;
    
    @Resource
    private ArticleMapper articleMapper;
    
    @Resource
    private IUserService userService;
    
    @Resource
    private IArticleService articleService;

    @Override
    public Long saveDraft(ArticleDraft draft) {
        if (draft == null || draft.getUserId() == null || draft.getUserId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 设置创建和更新时间
        Date now = new Date();
        if (draft.getCreateTime() == null) {
            draft.setCreateTime(now);
        }
        draft.setUpdateTime(now);
        
        if (draft.getId() != null && draft.getId() > 0) {
            // 更新已有草稿
            int row = articleDraftMapper.updateByPrimaryKeySelective(draft);
            if (row <= 0) {
                log.warn("更新草稿失败，草稿ID: {}", draft.getId());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
            }
            return draft.getId();
        } else {
            // 创建新草稿
            int row = articleDraftMapper.insertSelective(draft);
            if (row <= 0) {
                log.warn("创建草稿失败");
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
            }
            return draft.getId();
        }
    }

    @Override
    public ArticleDraft getDraftById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        ArticleDraft draft = articleDraftMapper.selectByPrimaryKey(id);
        if (draft == null) {
            log.warn("未找到草稿，ID: {}", id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        
        return draft;
    }

    @Override
    public List<ArticleDraft> getUserDrafts(Long userId) {
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        return articleDraftMapper.selectByUserId(userId);
    }

    @Override
    public boolean updateDraft(ArticleDraft draft) {
        if (draft == null || draft.getId() == null || draft.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 设置更新时间
        draft.setUpdateTime(new Date());
        
        int row = articleDraftMapper.updateByPrimaryKeySelective(draft);
        return row > 0;
    }

    @Override
    public boolean deleteDraft(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        int row = articleDraftMapper.deleteByPrimaryKey(id);
        return row > 0;
    }

    @Override
    @Transactional
    public Long publishDraft(Long draftId) {
        if (draftId == null || draftId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 获取草稿
        ArticleDraft draft = articleDraftMapper.selectByPrimaryKey(draftId);
        if (draft == null) {
            log.warn("未找到草稿，ID: {}", draftId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        
        // 验证用户存在
        User user = userService.selectById(draft.getUserId());
        if (user == null) {
            log.warn("发布草稿失败，用户不存在，用户ID: {}", draft.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        
        // 创建文章对象
        Article article = new Article();
        article.setUserId(draft.getUserId());
        article.setBoardId(draft.getBoardId());
        article.setTitle(draft.getTitle());
        article.setContent(draft.getContent());
        article.setTags(draft.getTags());
        article.setSummary(draft.getSummary());
        
        // 使用文章服务创建文章
        articleService.create(article);
        
        // 记录新创建的文章ID
        Long articleId = article.getId();
        log.info("从草稿创建文章成功，草稿ID: {}，新文章ID: {}", draftId, articleId);
        
        if (articleId == null) {
            log.warn("从草稿创建文章后获取的文章ID为null，这是异常情况");
            // 如果articleId为null，可能是因为文章对象没有正确获取自增ID
            // 可以考虑通过其他方式查询最新创建的文章
        }
        
        // 删除草稿
        articleDraftMapper.deleteByPrimaryKey(draftId);
        
        return articleId;
    }

    @Override
    public Long saveArticleAsDraft(Article article) {
        if (article == null || article.getUserId() == null || article.getUserId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 创建草稿对象
        ArticleDraft draft = new ArticleDraft();
        draft.setUserId(article.getUserId());
        draft.setBoardId(article.getBoardId());
        draft.setTitle(article.getTitle());
        draft.setContent(article.getContent());
        draft.setTags(article.getTags());
        draft.setSummary(article.getSummary());
        
        // 设置创建和更新时间
        Date now = new Date();
        draft.setCreateTime(now);
        draft.setUpdateTime(now);
        
        // 保存草稿
        int row = articleDraftMapper.insertSelective(draft);
        if (row <= 0) {
            log.warn("将文章保存为草稿失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        
        return draft.getId();
    }

    @Override
    public int countUserDrafts(Long userId) {
        if (userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        return articleDraftMapper.countByUserId(userId);
    }
} 